package ptij.ADSL.pn;

import ptolemy.kernel.*;
import ptolemy.kernel.util.*;
import ptolemy.data.*;
import ptolemy.data.expr.*;
import ptolemy.actor.*;
import ptolemy.domains.pn.kernel.*;

import java.util.Vector;
import java.io.*;

public class CustomerNetRx extends TypedAtomicActor {

    /* Input Ports */
    public TypedIOPort LS0;
    public TypedIOPort AS0;
    public TypedIOPort dataRx;

    public CustomerNetRx(TypedCompositeActor container, String name) throws
        NameDuplicationException, IllegalActionException {
        super(container, name);
    
        dataRx = new TypedIOPort(this, "dataRx", true, false);
	dataRx.setTypeEquals(IntToken.class);
	    
        AS0 = new TypedIOPort(this, "AS0", true, false);
	AS0.setTypeEquals(ObjectToken.class);
	
	LS0 = new TypedIOPort(this, "LS0", true, true);
	LS0.setTypeEquals(ObjectToken.class);
    }

    public void fire() throws IllegalActionException {

        IntToken it = (IntToken) dataRx.get(0);
	ObjectToken ot;
	int [] tmp = null;
		
	switch(it.intValue()) {
	    case 0 : {
	        ot = (ObjectToken) AS0.get(0);
	        tmp = (int []) ot.getValue();
	        for(int i = 0;i < tmp.length;i++) {
	            _AS0Data.insertElementAt(new Byte((byte)tmp[i]),
		            _AS0Counter);
		    _AS0Counter++;
	        }
	    } break;
	    
	    case 1 : {
	        ot = (ObjectToken) LS0.get(0);
	        tmp = (int []) ot.getValue();
	        for(int i = 0;i < tmp.length;i++) {
	            _LS0Data.insertElementAt(new Byte((byte)tmp[i]), 
		            _LS0Counter);
		    _LS0Counter++;
	        }
	    } break;
	}
    }
    
    public void initialize() throws IllegalActionException {
        super.initialize();
	
	_AS0Data = new Vector();
	_LS0Data = new Vector();
	
	_AS0Counter = 0;
	_LS0Counter = 0;
    }

    public void wrapup() throws IllegalActionException {
        super.wrapup();
        try {
            File f = new File("as0_r.rx");
            FileOutputStream fo = new FileOutputStream(f);
            DataOutputStream data = new DataOutputStream(fo);
            
	    for(int i = 0;i < _AS0Data.size();i++) {
	        Byte b = (Byte) _AS0Data.elementAt(i);
		data.write(b.byteValue());
	    }
	    
	    data.close();
	    fo.close();

            f = new File("ls0_r.rx");
            fo = new FileOutputStream(f);
            data = new DataOutputStream(fo);
            
	    for(int i = 0;i < _LS0Data.size();i++) {
	        Byte b = (Byte) _LS0Data.elementAt(i);
		data.write(b.byteValue());
	    }	    
	    data.close();
	    fo.close();
	} 
	catch(IOException ex) {
	    System.out.println(ex);
	}
    }
    
    private Vector _AS0Data;
    private Vector _LS0Data;
    private int _AS0Counter;
    private int _LS0Counter;
}
